package com.modules.content.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.response.ResponseVO;
import com.common.exception.RRException;
import com.common.utils.R;
import com.modules.content.VO.ContentsVO;
import com.modules.content.entity.Contents;
import com.modules.content.service.IContentsService;
import com.modules.contentImages.entity.ContentImages;
import com.modules.contentImages.service.IContentImagesService;
import com.modules.system.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/contents")
public class ContentsController {

    @Autowired
    private IContentsService contentsService;
    @Autowired
    private IAdminService adminService;
    @Autowired
    private IContentImagesService contentImagesService;

    // 贴图分页列表
    @RequestMapping("/getPageList")
    public R getPageList(@RequestParam Map<String, Object> params){
        return contentsService.getPageList(params);
    }

    // 获得单个贴图信息
    @GetMapping ("/getEntityById/{id}")
    public R getEntityById(@PathVariable Integer id){
        Contents content = contentsService.getOne(new QueryWrapper<Contents>().lambda().eq(Contents::getId, id));
        if (content == null){
            throw new RRException("贴图不存在");
        }
        // 复制出VO对象，方便设置图片信息
        ContentsVO contentsVO = BeanUtil.copyProperties(content, ContentsVO.class);

        // 查找关联的图片信息
        List<ContentImages> contentImagesList = contentImagesService.list(new QueryWrapper<ContentImages>().lambda()
        .eq(ContentImages::getContentid, content.getId())
        .orderByAsc(ContentImages::getSort));
        contentsVO.setContentImages(contentImagesList);

        return R.ok().put("data", contentsVO);
    }

    // 添加/编辑 贴图
    @PostMapping("/saveEntity")
    public R saveEntity(@RequestBody ContentsVO content, @RequestParam Integer adminId){
        return contentsService.saveEntity(content, adminId);
    }

    // 删除贴图
    @DeleteMapping("/removeEntity/{id}")
    public R removeEntity(@PathVariable Integer id){
        Contents content = contentsService.getOne(new QueryWrapper<Contents>().lambda().eq(Contents::getId, id));
        if (content == null){
            throw new RRException("贴图不存在");
        }
        contentsService.removeById(content);
        return R.ok();
    }
}
